package com.tzbank.voice.service.impl;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tzbank.redis.RedisUtils;
import com.tzbank.utils.HttpClientUtil;
import com.tzbank.utils.ResultUtil;
import com.tzbank.voice.dao.VoiceMapper;
import com.tzbank.voice.entity.VoiceFlowRecord;
import com.tzbank.voice.entity.VoiceModel;
import com.tzbank.voice.service.VoiceService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service(value = "voiceService")
@Slf4j
public class VoiceServiceImpl implements VoiceService {

	@Autowired
	private VoiceMapper voiceMapper;

	// ApiKey创建应用时自动生成
	private String apiKey = "";
	private String xAppid = "";
	private String url = "";

	/**
	 * 获取必要参数
	 * 
	 * @return
	 * @return
	 */
	public void getVoiceConfig() {
		apiKey = RedisUtils.getValue("VOICE_APIKEY");
		xAppid = RedisUtils.getValue("VOICE_XAPPID");
		url = RedisUtils.getValue("VOICE_URL");
	}

	@Transactional
	public Map<String, Object> voiceTranslation_v2(VoiceModel vo) {
		
		getVoiceConfig();// 获取必要的配置信息
		log.info("---------->语音------->begin");
		String voiceString = "";
		String data = "";
		String code = "";
		String msg = "";
		String auth_uuid=UUID.randomUUID().toString().replaceAll("-", "");
		// 当前UTC时间戳
		String curTime = System.currentTimeMillis() / 1000L + "";
		String xParam = "{\"data_type\":\"" + vo.getData_type() + "\",\"scene\":\"" + vo.getScene() +"\",\"auth_id\":\""+auth_uuid+"\"}";
		// 相关参数json串经base64编码后的字符串
		String xParamBase64 = "";
		// 令牌，MD5（apiKey+curTime+xParamBase64）
		String xCheckSum = "";

		try {
			xParamBase64 = new String(Base64.encodeBase64(xParam.getBytes("utf-8")));
			xCheckSum = DigestUtils.md5Hex(apiKey + curTime + xParamBase64);
		} catch (UnsupportedEncodingException e1) {
			log.info("---------->语音----封装参数异常--->end>", e1);
		}
		// 音频文件base64编码后的字符串
		
		/* 操作流水记录 */
		VoiceFlowRecord vocieFlowRecord = new VoiceFlowRecord();
		vocieFlowRecord.setOperatingUser(vo.getUserId());// 操作用户'
		vocieFlowRecord.setRequesSource(vo.getRequestSource());// 请求来源
		vocieFlowRecord.setCorrespondingInterface("语音语义分析");// 对应接口
		vocieFlowRecord.setConsumerSeqNo(vo.getConsumerSeqNo());
		//20180628//新加
		vocieFlowRecord.setAddress(vo.getAddress());//地址
		vocieFlowRecord.setBusinessScenario(vo.getBusinessScenario());//业务场景
		//20180628//结束
		byte[] bytes = null;	
		if ("audio".equalsIgnoreCase(vo.getData_type())) {			
			 bytes = Base64.decodeBase64(vo.getData());
		}else {
			 bytes =vo.getData().getBytes();
		}
		
		try {
			// 发生请求，获取返回结果
			voiceString = HttpClientUtil.sendPost(url, xAppid, curTime, xParamBase64, xCheckSum,bytes);		
			JSONObject result  = JSONObject.fromObject(voiceString); // 字符转对象， 需要添加try
			JSONArray a= JSONArray.fromObject(result.getString("data")) ;
			
			for (int i = 0; i < a.size(); i++) {
				JSONObject ss=(JSONObject) a.get(i);
				String type=(String) ss.get("sub");
				if("iat".equals(type)) {
					//文字
					String text=(String) ss.get("text");
					if(!"".equals(text)) {
						data = JSONObject.fromObject(a.get(i).toString()).toString() ;
					}
					
				}else {
					//语音
					JSONObject d=(JSONObject) ss.get("intent");
					if(d.size()==0) {
						System.out.println("语音结果：空");
					}else {
						data = JSONObject.fromObject(a.get(i).toString()).toString();
					}
				}
		}	
			
//2018.0.9注释
/*			if ("audio".equalsIgnoreCase(vo.getData_type())) {
				data = JSONObject.fromObject(a.get(1).toString()).toString() ;
			}else {
				data = JSONObject.fromObject(a.get(0).toString()).toString() ;
			}	*/		
			code = result.getString("code");
			msg = result.getString("desc");
			/* 操作流水记录 */
			String logdata="";
			if ("audio".equalsIgnoreCase(vo.getData_type())) {
				 logdata = vo.getData().substring(0);// 截取一段音频base64码
			}else {
				 logdata = vo.getData();
			}
			vo.setData(logdata);
			vocieFlowRecord.setRequestParameters(vo.toString());// 请求参数
			vocieFlowRecord.setResponseResult("[" + msg + "---" + code + "---" + data + "]");// 返回结果
			insertRecord(vocieFlowRecord);

		} catch (Exception e) {
			/* 操作流水记录 */
			vocieFlowRecord.setResponseResult("[语音无法识别~---500]");// 返回结果
			insertRecord(vocieFlowRecord);
			log.info("---------->语音----异常报错--->end>", e);
			return ResultUtil.resultMap("语音无法识别~", "500", null);
		}
		log.info("---------->语音----成功运行--->end");
		return ResultUtil.resultMap(msg, code, data);
	}
	
	
	
	/**
	 * 操作流水记录
	 * 
	 */
	public void insertRecord(VoiceFlowRecord vocieFlowRecord) {

		Calendar cal = Calendar.getInstance();
		vocieFlowRecord.setYear(String.valueOf(cal.get(Calendar.YEAR)));
		vocieFlowRecord.setMonth(String.valueOf(cal.get(Calendar.MONTH) + 1));
		voiceMapper.intoVoiceLog(vocieFlowRecord);

	}

	

}
